<template>
  <div class="merchant-edit">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="router.back()">
          <i class="fas fa-arrow-left"></i> 返回
        </el-button>
        <h2>{{ isEdit ? "编辑商家" : "新增商家" }}</h2>
      </div>
      <div class="header-right">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </div>

    <el-card class="edit-card">
      <el-form
        ref="merchantFormRef"
        :model="merchantForm"
        :rules="merchantFormRules"
        label-width="120px"
        class="merchant-form"
      >
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商家名称" prop="name">
                <el-input
                  v-model="merchantForm.name"
                  placeholder="请输入商家名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家类型" prop="type">
                <el-select
                  v-model="merchantForm.type"
                  placeholder="请选择商家类型"
                >
                  <el-option label="酒店" value="hotel" />
                  <el-option label="景点" value="scenic" />
                  <el-option label="文创商家" value="cultural" />
                  <el-option label="餐饮" value="food" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contact">
                <el-input
                  v-model="merchantForm.contact"
                  placeholder="请输入联系人"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="phone">
                <el-input
                  v-model="merchantForm.phone"
                  placeholder="请输入联系电话"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商家地址" prop="address">
            <el-input
              v-model="merchantForm.address"
              placeholder="请输入商家地址"
            />
          </el-form-item>

          <el-form-item label="商家简介" prop="description">
            <el-input
              type="textarea"
              v-model="merchantForm.description"
              :rows="3"
              placeholder="请输入商家简介"
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商家Logo" prop="logo">
                <el-upload
                  class="avatar-uploader"
                  action="/api/upload"
                  :show-file-list="false"
                  :on-success="handleLogoSuccess"
                  :before-upload="beforeLogoUpload"
                >
                  <img
                    v-if="merchantForm.logo"
                    :src="merchantForm.logo"
                    class="avatar"
                  />
                  <el-icon v-else class="avatar-uploader-icon">
                    <i class="fas fa-plus"></i>
                  </el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <h3 class="section-title">营业信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="营业时间" prop="businessHours">
                <el-time-picker
                  v-model="merchantForm.businessHours[0]"
                  placeholder="开始时间"
                  format="HH:mm"
                  :default-time="new Date(2000, 1, 1, 9, 0)"
                />
                <span class="time-separator">至</span>
                <el-time-picker
                  v-model="merchantForm.businessHours[1]"
                  placeholder="结束时间"
                  format="HH:mm"
                  :default-time="new Date(2000, 1, 1, 18, 0)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家标签" prop="tags">
                <el-select
                  v-model="merchantForm.tags"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择或输入标签"
                >
                  <el-option
                    v-for="tag in tagOptions"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <h3 class="section-title">资质信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="法人姓名" prop="legalPerson">
                <el-input
                  v-model="merchantForm.legalPerson"
                  placeholder="请输入法人姓名"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idCard">
                <el-input
                  v-model="merchantForm.idCard"
                  placeholder="请输入身份证号"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="营业执照" prop="license">
            <el-upload
              class="license-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleLicenseSuccess"
              :before-upload="beforeLicenseUpload"
            >
              <img
                v-if="merchantForm.license"
                :src="merchantForm.license"
                class="license"
              />
              <el-icon v-else class="license-uploader-icon">
                <i class="fas fa-plus"></i>
              </el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="其他资质" prop="qualifications">
            <el-upload
              class="qualification-uploader"
              action="/api/upload"
              list-type="picture-card"
              :file-list="qualificationList"
              :on-success="handleQualificationSuccess"
              :before-upload="beforeQualificationUpload"
              :on-remove="handleQualificationRemove"
            >
              <i class="fas fa-plus"></i>
            </el-upload>
          </el-form-item>
        </div>

        <div class="form-section">
          <h3 class="section-title">结算信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开户银行" prop="bankName">
                <el-input
                  v-model="merchantForm.bankName"
                  placeholder="请输入开户银行"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行账号" prop="bankAccount">
                <el-input
                  v-model="merchantForm.bankAccount"
                  placeholder="请输入银行账号"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import service from "@/api/axios";

const route = useRoute();
const router = useRouter();
const merchantId = route.params.id;
const isEdit = !!merchantId;

const merchantFormRef = ref(null);
const merchantForm = reactive({
  name: "",
  type: "",
  contact: "",
  phone: "",
  address: "",
  description: "",
  logo: "",
  businessHours: [new Date(2000, 1, 1, 9, 0), new Date(2000, 1, 1, 18, 0)],
  tags: [],
  legalPerson: "",
  idCard: "",
  license: "",
  qualifications: [],
  bankName: "",
  bankAccount: "",
});

const qualificationList = ref([]);

// 表单验证规则
const merchantFormRules = {
  name: [{ required: true, message: "请输入商家名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择商家类型", trigger: "change" }],
  contact: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  address: [{ required: true, message: "请输入商家地址", trigger: "blur" }],
  legalPerson: [{ required: true, message: "请输入法人姓名", trigger: "blur" }],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
  bankName: [{ required: true, message: "请输入开户银行", trigger: "blur" }],
  bankAccount: [
    { required: true, message: "请输入银行账号", trigger: "blur" },
    {
      pattern: /^\d{16,19}$/,
      message: "请输入正确的银行账号",
      trigger: "blur",
    },
  ],
};

// 标签选项
const tagOptions = [
  "24小时营业",
  "提供WiFi",
  "停车方便",
  "环境优美",
  "服务周到",
  "价格实惠",
];

// Logo上传
const handleLogoSuccess = (res, file) => {
  if (res && res.code === 200) {
    merchantForm.logo = res.data.url;
  } else {
    // 本地测试
    merchantForm.logo = URL.createObjectURL(file.raw);
  }
};

const beforeLogoUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传头像图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 营业执照上传
const handleLicenseSuccess = (res, file) => {
  if (res && res.code === 200) {
    merchantForm.license = res.data.url;
  } else {
    // 本地测试
    merchantForm.license = URL.createObjectURL(file.raw);
  }
};

const beforeLicenseUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传营业执照只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("上传营业执照大小不能超过 5MB!");
    return false;
  }
  return true;
};

// 其他资质上传
const handleQualificationSuccess = (res, file) => {
  if (res && res.code === 200) {
    merchantForm.qualifications.push(res.data.url);
    qualificationList.value.push({
      name: file.name,
      url: res.data.url
    });
  } else {
    // 本地测试
    const url = URL.createObjectURL(file.raw);
    merchantForm.qualifications.push(url);
    qualificationList.value.push({
      name: file.name,
      url: url
    });
  }
};

const beforeQualificationUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传资质图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("上传资质图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

const handleQualificationRemove = (file) => {
  const index = qualificationList.value.findIndex(
    (item) => item.url === file.url,
  );
  if (index !== -1) {
    qualificationList.value.splice(index, 1);
    merchantForm.qualifications.splice(index, 1);
  }
};

// 获取商家信息
const fetchMerchantData = async () => {
  try {
    if (!merchantId) return;
    
    const response = await service.get(`/admin/merchants/${merchantId}`);
    if (response.code === 200) {
      Object.assign(merchantForm, response.data);

      // 处理资质图片列表
      if (response.data.qualifications) {
        qualificationList.value = response.data.qualifications.map((url) => ({
          name: url.split("/").pop(),
          url,
        }));
      }
    } else {
      // 使用测试数据
      const mockData = {
        name: "贵港大酒店",
        type: "hotel",
        contact: "张经理",
        phone: "13800138000",
        address: "广西贵港市港北区中山路128号",
        description: "贵港市中心地段的四星级酒店，环境优雅，设施完善",
        logo: "https://example.com/logo1.png",
        businessHours: [new Date(2000, 1, 1, 8, 0), new Date(2000, 1, 1, 22, 0)],
        tags: ["商务酒店", "会议服务", "餐饮"],
        legalPerson: "张三",
        idCard: "450800198001011234",
        license: "https://example.com/license1.jpg",
        bankName: "中国工商银行贵港支行",
        bankAccount: "6222021234567890123",
        qualifications: [
          { name: "卫生许可证.jpg", url: "https://example.com/qual1.jpg" },
          { name: "消防安全证.jpg", url: "https://example.com/qual2.jpg" },
        ],
      };
      
      Object.assign(merchantForm, mockData);
      
      // 处理资质图片列表
      if (mockData.qualifications) {
        qualificationList.value = mockData.qualifications;
      }
    }
  } catch (error) {
    console.error("获取商家信息失败:", error);
    ElMessage.error("获取商家信息失败");
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!merchantFormRef.value) return;

  try {
    await merchantFormRef.value.validate();

    const formData = { ...merchantForm };
    
    // 转换时间格式
    if (formData.businessHours && formData.businessHours.length === 2) {
      formData.businessHours = formData.businessHours.map(time => {
        if (time instanceof Date) {
          return `${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`;
        }
        return time;
      });
    }
    
    let response;
    if (isEdit) {
      // 更新商家
      response = await service.put(`/admin/merchants/${merchantId}`, formData);
    } else {
      // 新增商家
      response = await service.post('/admin/merchants', formData);
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit ? "保存成功" : "添加成功");
      handleCancel();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  }
};

// 取消
const handleCancel = () => {
  router.back();
};

onMounted(() => {
  fetchMerchantData();
});
</script>

<style lang="less" scoped>
.merchant-edit {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;

    h2 {
      margin: 0;
      font-size: 24px;
    }
  }

  .header-right {
    display: flex;
    gap: 12px;
  }
}

.edit-card {
  margin-bottom: 20px;
}

.merchant-form {
  max-width: 1200px;
  margin: 0 auto;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  margin: 0 0 20px;
  color: var(--el-text-color-primary);
}

.time-separator {
  margin: 0 10px;
}

.avatar-uploader,
.license-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader .avatar,
.license-uploader .license {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader-icon,
.license-uploader-icon {
  width: 178px;
  height: 178px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader-icon i,
.license-uploader-icon i {
  font-size: 28px;
  color: #8c939d;
}

.qualification-uploader {
  :deep(.el-upload--picture-card) {
    width: 148px;
    height: 148px;
    line-height: 148px;
  }
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-light);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .merchant-edit {
    padding: 12px;
  }

  .page-header h2 {
    font-size: 20px;
  }

  .section-title {
    font-size: 16px;
  }

  .el-form-item {
    margin-bottom: 18px;
  }

  .avatar-uploader .avatar,
  .license-uploader .license,
  .avatar-uploader-icon,
  .license-uploader-icon {
    width: 120px;
    height: 120px;
  }
}
</style>
